<template>
  <div class="table-wrapper" style="height: 300px">
    <avic-table
      :columns="userConfigColumns"
      :row-key="(record) => record.nodeId"
      :data-source="nodeCandidateList"
      :loading="loading"
      :row-selection="null"
      :show-table-setting="false"
      :pagination="false"
      style="height: 100%"
    >
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'nodeId'">
          <span :title="index + 1">
            {{ index + 1 }}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'taskName'">
          <a-input v-model:value="record.taskName" placeholder="请输入任务名称" style="width: 100%" />
        </template>
        <template v-else-if="column.dataIndex === 'responsibleUnitId'">
          <AvicCommonSelect
            v-model:value="record.responsibleUnitId"
            :default-show-value="record.responsibleUnitName"
            :org-checkable="true"
            placeholder="请选择"
            type="deptSelect"
            @callback="
              (value, selectRows) => {
                if (selectRows.length > 0) {
                  const nodeType = selectRows[0].nodeType;
                  if (nodeType === 'dept') {
                    record.orgId = selectRows[0].attributes.ownOrgId;
                  } else {
                    record.orgId = value.ids;
                  }
                  record.orgType = nodeType;
                } else {
                  record.orgId = '';
                  record.orgType = '';
                }
                record.responsibleUnitId = value.ids;
                record.responsibleUnitName = value.names;
              }
            "
          />
        </template>
        <template v-else-if="column.dataIndex === 'userId'">
          <AvicCommonSelect
            v-model:value="record.userId"
            :default-show-value="record.userName"
            placeholder="请选择"
            :default-org-id="record.orgId"
            :default-load-dept-id="record.orgType === 'dept' && record.orgId ? record.responsibleUnitId : ''"
            type="userSelect"
            @callback="
              (value) => {
                record.userName = value.names;
                record.deptId = value.deptid;
                record.deptName = value.deptname;
              }
            "
          />
        </template>
        <template v-else-if="column.dataIndex === 'planCompleteTime'">
          <a-date-picker
            v-model:value="nodeCandidateList[index].planCompleteTime"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划完成时间"
          />
        </template>
      </template>
    </avic-table>
  </div>
</template>
<script setup lang="ts">
import { getBpmPiActivityListByProcessKey } from '@/api/avic/bpmpi/BpmPiInstanceApi';
const { proxy } = getCurrentInstance();
const props = defineProps({
  /** 过程定义Id */
  defineId: {
    required: true,
    type: String
  }
});
const nodeCandidateList = ref([]);
const loading = ref(false);

// 监听过程定义Id变化，加载过程配置
watch(
  () => props.defineId,
  (newV) => {
    if (newV) {
      loadUserConfig();
    }
  },
  { immediate: true }
);

// 过程节点人员配置
const userConfigColumns = [
  {
    title: '序号',
    dataIndex: 'nodeId',
    ellipsis: true,
    width: 60,
    align: 'center',
    fixed: 'left'
  },
  {
    title: '过程节点',
    dataIndex: 'label',
    minWidth: 60,
    align: 'center',
    fixed: 'left'
  },
  {
    title: '任务名称',
    dataIndex: 'taskName',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left',
    customHeaderCell() {
      // 必填设置
      return {
        ['class']: 'required-table-title'
      };
    }
  },
  {
    title: '责任单位/部门',
    dataIndex: 'responsibleUnitId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left',
    customHeaderCell() {
      // 必填设置
      return {
        ['class']: 'required-table-title'
      };
    }
  },
  {
    title: '过程处理人',
    minWidth: 60,
    dataIndex: 'userId',
    customHeaderCell() {
      // 必填设置
      return {
        ['class']: 'required-table-title'
      };
    }
  },
  {
    title: '计划完成时间',
    dataIndex: 'planCompleteTime',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left',
    customHeaderCell() {
      // 必填设置
      return {
        ['class']: 'required-table-title'
      };
    }
  }
];

onMounted(() => {});

function loadUserConfig() {
  loading.value = true;
  nodeCandidateList.value = [];
  loadProcessModel()
    .then((res: any) => {
      if (res) {
        nodeCandidateList.value = [];
        res.forEach((node: any) => {
          if (node.component !== 'start' && node.component !== 'end') {
            const nodeData = {
              nodeId: node.name,
              label: node.alias,
              taskName: node.alias,
              userId: '',
              deptId: '',
              responsibleUnitId: '',
              planCompleteTime: null
            };
            nodeCandidateList.value.push(nodeData);
          }
        });
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
      proxy.$message.warning('获取过程数据失败！');
    });
}
/**
 * 收集节点配置数据用于保存
 */
function saveData() {
  if (nodeCandidateList.value && nodeCandidateList.value.length > 0) {
    const firstCandidate = nodeCandidateList.value[0];
    if (!firstCandidate.responsibleUnitId) {
      proxy.$message.warning(`【${firstCandidate.label}】节点责任单位/部门不能为空`);
      return null;
    }
    if (!firstCandidate.userId) {
      proxy.$message.warning(`【${firstCandidate.label}】节点责任人不能为空`);
      return null;
    }
    if (!firstCandidate.planCompleteTime) {
      proxy.$message.warning(`【${firstCandidate.label}】节点计划完成时间不能为空`);
      return null;
    }
    return nodeCandidateList.value;
  }
  proxy.$message.warning('当前事项类别未找到相应的过程信息');
  return null;
}
defineExpose({
  saveData
});
function loadProcessModel() {
  if (props.defineId) {
    return new Promise((resolve) => {
      getBpmPiActivityListByProcessKey(props.defineId).then((res: any) => {
        if (res.success) {
          resolve(res.data || {});
        }
      });
    });
  }
  return Promise.reject();
}
</script>
